package com.cpecc.controller.system;

import com.cpecc.manager.system.UserManager;
import com.cpecc.model.system.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
public class SSOController {
	
	@Autowired
	private UserManager userManager;
	
	private final static String MD5(String s) {
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'A', 'B', 'C', 'D', 'E', 'F' };
		try {
			byte[] btInput = s.getBytes();
			// 获得MD5摘要算法的 MessageDigest 对象
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			// 使用指定的字节更新摘要
			mdInst.update(btInput);
			// 获得密文
			byte[] md = mdInst.digest();
			// 把密文转换成十六进制的字符串形式
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@RequestMapping(value = "/ssologin")
	public ModelAndView ssologin(String username,String code, HttpSession session){
		ModelAndView mav = new ModelAndView();
		Subject currentUser = SecurityUtils.getSubject();
		if(username!=null && !username.equals("") && code!=null && !code.equals("")){
			String md5Str=MD5(username);
			md5Str+="CPECC";
			md5Str=MD5(md5Str);
			Date date=new Date();
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
			String riQi=sdf.format(date);
			md5Str+=riQi;
			md5Str=MD5(md5Str);
			if(md5Str.equals(code)){
				User user=userManager.findByUsername(username);
				UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(),user.getPassword());
				token.setRememberMe(false);
				try {
					currentUser.login(token);
				} catch (UnknownAccountException uae) {
					mav.addObject("message", "用户名密码错误!");			
				} catch (IncorrectCredentialsException ice) {
					mav.addObject("message", "用户名密码错误!");			
				} catch (LockedAccountException lae) {
					mav.addObject("message", "账户被锁定!");			
				} catch (ExcessiveAttemptsException eae) {
					mav.addObject("message", "认证失败!");			
				} catch (AuthenticationException ae) {
					mav.addObject("message", "登录失败!");			
				}
				if(currentUser.isAuthenticated()){
					if(userManager.findByUsername(user.getUserName()).isLocked()){
						mav.addObject("message", "账户被锁定!");
						mav.setViewName("redirect:/login.jsp");
					}else if(user.getDep().getId().equals("888888")){
						mav.addObject("message", "未定义部门，请联系固资管理员!");
						mav.setViewName("redirect:/login.jsp");
					}else{
						session.setAttribute("userinfo", user);
						session.setAttribute("code", getUserCode(user.getUserName()));
						mav.setViewName("redirect:/tixing/shouye.do");
					}
				}else{
					mav.addObject("message", "用户名密码错误!");
					mav.setViewName("redirect:/login.jsp");
				}
				return mav;
			}
		}
		mav.addObject("message", "用户名密码错误!");
		mav.setViewName("redirect:/login.jsp");
		return mav;
	}

	private String getUserCode(String username) {
		if (username == null || "".equals(username)) {
			return null;
		}

		String md5Str = MD5(username) + "CPECC";
		md5Str = MD5(md5Str);

		Date date=new Date();
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		String riQi = sdf.format(date);
		md5Str += riQi;

		return MD5(md5Str);
	}
}
